package com.org.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.org.config.Configurations;
import com.org.util.IoUtil;
import com.org.util.Range;
import com.org.util.TokenUtil;

@RestController
public class DownsClientController {
	static final String FILE_NAME_FIELD = "name";
	static final String FILE_SIZE_FIELD = "size";
	static final String TOKEN_FIELD = "token";
	static final String SERVER_FIELD = "server";
	static final String SUCCESS = "success";
	static final String MESSAGE = "message";
	static final int BUFFER_LENGTH = 102400;
	static final String START_FIELD = "start";
	public static final String CONTENT_RANGE_HEADER = "content-range";
	static final String FILE_FIELD = "file";
	@RequestMapping("findfile")
	public String findDownFile(HttpServletRequest request,HttpServletResponse response) {
		String strURL =request.getParameter("strUrl");
		long start = 0;
		boolean success = true;
		String message = "";
		JSONObject json = new JSONObject();
		String filename="";
		String token ="";
		int contentLength=0;
		try {
		URL downUrl = new URL(strURL);
		HttpURLConnection conn = (HttpURLConnection) downUrl.openConnection();
		if (conn.getResponseCode() == 200) {
			// InputStream is = cn.getInputStream();
			String contentDisposition = new String(conn.getHeaderField("Content-Disposition").getBytes("ISO-8859-1"), "UTF-8");
	        filename=contentDisposition.substring(contentDisposition.lastIndexOf("=")+1);
		    contentLength = conn.getContentLength();
			System.out.println("cn.getContentLength():" + conn.getContentLength());
			conn.disconnect();
			 token = TokenUtil.generateToken(filename, contentLength+"");
			File f = IoUtil.getTokenedFile(token,"");
			start = f.length();
			System.out.println("起始大小"+start);
			if (token.endsWith("_0") && "0".equals(contentLength+"") && 0 == start)
				f.renameTo(IoUtil.getFile(filename));
		}
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				if (success)
			    json.put(FILE_NAME_FIELD, filename);
				json.put(FILE_SIZE_FIELD, contentLength);
			    json.put(START_FIELD, start);
				json.put(SUCCESS, success);
				json.put(MESSAGE, message);
				json.put("url", strURL);
				json.put(TOKEN_FIELD, token);
			} catch (JSONException e) {}
		}
		return json.toJSONString();
	}
	@RequestMapping("getFile")
	public void getFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
		final PrintWriter writer = response.getWriter();
		byte[] buf = new byte[10240];
		int size;
		Long start=0L;
		boolean success = true;
		String message = "";
		JSONObject json = new JSONObject();
		final String token = request.getParameter(TOKEN_FIELD);
		final String fileName = request.getParameter(FILE_NAME_FIELD);
		String strURL=request.getParameter("url");
		HttpURLConnection httpURLConnection;
		URL url;
		File f = IoUtil.getTokenedFile(token,"");
		start = f.length();
		  Range range = IoUtil.parseRange(request);
		 //String rangeStr = request.getHeader(CONTENT_RANGE_HEADER);
		// 获取输入流
		OutputStream out = null;
		InputStream content = null;
		// 下载文件
		try {
			url = new URL(strURL);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			// 设置User-Agent
			httpURLConnection.setRequestProperty("User-Agent", "Net");
			// 设置续传开始
			httpURLConnection.setRequestProperty("Range", "bytes=" + range.getFrom() + "-"+range.getTo());
			content = new BufferedInputStream(httpURLConnection.getInputStream());
			out = new FileOutputStream(f, true);
			while ((size = content.read(buf)) != -1) {
				out.write(buf, 0, size);
			}
			httpURLConnection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			IoUtil.close(out);
			IoUtil.close(content);
			/** rename the file */
			if (range.getSize() == start) {
				try {
					// 先删除
					IoUtil.getFile(fileName).delete();
					Files.move(f.toPath(), f.toPath().resolveSibling(fileName));
					System.out.println("TK: `" + token + "`, NE: `" + fileName + "`");
					if (Configurations.isDeleteFinished()) {
						IoUtil.getFile(fileName).delete();
					}
				} catch (IOException e) {
					success = false;
					message = "Rename file error: " + e.getMessage();
				}
				
			}
			try {
				if (success)
			    json.put(FILE_NAME_FIELD, fileName);
				json.put(FILE_SIZE_FIELD, range.getSize());
			    json.put(START_FIELD, start);
				json.put(SUCCESS, success);
				json.put(MESSAGE, message);
				json.put("url", strURL);
				json.put(TOKEN_FIELD, token);
			} catch (JSONException e) {}
			
			writer.write(json.toString());
			IoUtil.close(writer);
		}
	}
		
}
